package com.sfang.common.base.http.Interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.sfang.common.base.token.SaUserInfo;
import com.sfang.common.base.token.TokenUtils;
import com.sfang.common.base.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import com.sfang.common.base.http.Interceptor.BodyReaderRequestWrapper;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Map;

/**
 * http日志拦截器
 *
 * @author xuzilou
 * @date 2021/3/24 16:20
 */
@Slf4j
@Component
public class HttpLogInterceptor implements HandlerInterceptor {

    @Resource
    private TokenUtils tokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            request.setAttribute("startTime_xzl", System.currentTimeMillis());
            String requestUri = request.getRequestURI();
            String method = request.getMethod();
            String body = getBody(request);
            log.info("http request url:{},ip:{},method:{},oauthTokenPayload:{},queryString:{},body:{}",
                    requestUri,
                    IpUtil.getClientIpAddress(request),
                    method,
                    request.getHeader("tokenPayload"),
                    request.getQueryString(),
                    body);
            if (StrUtil.contains(requestUri, "sa-admin")) {
                JSONObject token = tokenUtils.getJSONObjectByToken();
                if (ObjectUtil.isNotEmpty(token)) {
                }
            } else if (StrUtil.contains(requestUri, "sa-tenant")) {
                SaUserInfo saUserInfo = tokenUtils.getSaUserInfo();
                if (BeanUtil.isNotEmpty(saUserInfo)) {
                }
            }
        } catch (Exception e) {
            log.info("httpLogInterceptor preHandle error:{}", e.getMessage());
        }
        return true;
    }

    /**
     * 获取bode 文件上传跳过
     *
     * @param request 请求
     * @return 请求body
     */
    private String getBody(HttpServletRequest request) {
        if (request instanceof BodyReaderRequestWrapper) {
            try {
                return StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
            } catch (IOException e) {
                log.error("read inputStream error:", e);
            }
        }
        return "";
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        try {
            Long startTime = (Long) request.getAttribute("startTime_xzl");
            String responseJson = (String) request.getAttribute("response_xzl");
            String requestUri = request.getRequestURI();
            log.info("http response url:{},result:{},spendTime:{}ms", requestUri, StrUtil.sub(responseJson, 0, 2000), System.currentTimeMillis() - startTime);
        } catch (Exception e) {
            log.info("print log error:{}", e.getMessage());
        } finally {
        }
    }

    /**
     * 获取所有头信息
     *
     * @param request http请求
     * @return {@link Map<String,Object>}
     */
    private Map<String, Object> getHeaders(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, Object> headers = Maps.newHashMap();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headers.put(headerName, request.getHeader(headerName));
        }
        return headers;
    }

}
